//
//  AppDelegate+AppService.m
//  XiangLove
//
//  Created by Dgh Hv on 2018/10/15.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "AppDelegate+AppService.h"
#import <AvoidCrash.h>

static CLLocationManager *locationManager;
@implementation AppDelegate (AppService)

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


-(void)initAvoidCrash
{
    // 1 开始监听
    [AvoidCrash becomeEffective];
    // 2 监听通知:AvoidCrashNotification, 获取AvoidCrash捕获的崩溃日志的详细信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
}

- (void)dealwithCrashMessage:(NSNotification *)note {
    //注意:所有的信息都在userInfo中
    //可以在这里收集相应的崩溃信息进行相应的处理(比如传到自己服务器)
    NSLog(@"崩溃信息----%@",note.userInfo);
}

- (void)getCurrentLocation
{
    //初始化定位管理器
    locationManager = [[CLLocationManager alloc]init];
    //设置代理
    locationManager.delegate = self;
    //定位精准度
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    //横向移动多少距离后更新位置信息
    locationManager.distanceFilter = 1000;
    //ios8以后需要获取定位权限
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [locationManager requestWhenInUseAuthorization];
    }
    [self dingwei];
}

- (void)dingwei{//判断定位是否开启
    if ([CLLocationManager locationServicesEnabled]){//  判断用户是否允许程序获取位置权限
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse||[CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways){
            //用户允许获取位置权限//开始定位
            [locationManager startUpdatingLocation];
        }else{
            //用户拒绝开启用户权限
            [locationManager startUpdatingLocation];
        }
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"开启定位服务" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启),才能看到附近的人" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            NSLog(@"点击确认");
            
        }]];
        [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
    }
    
}


#pragma mark - CLLocationManagerDelegate
// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取经纬度
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    // 停止位置更新
    [manager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //当前所在城市的坐标值
    CLLocation *currLocation = [locations lastObject];
    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
    //根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            NSDictionary *address = [placemark addressDictionary];
            [kUserDefaults setObject:SafeStr([address objectForKey:@"City"]) forKey:KUserNowCity];
            [kUserDefaults setObject:NSStringFormat(@"%f",currLocation.coordinate.latitude) forKey:KUserNowLatitude];
            [kUserDefaults setObject:NSStringFormat(@"%f",currLocation.coordinate.longitude) forKey:KUserNowLongitude];
            [kUserDefaults synchronize];
            [manager stopUpdatingLocation];

        }
    }];
    
}
// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}

-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}


@end
